package com.sjf.JavaNIO.channel;

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 用于从文件中读取字节数据到buffer缓冲区中
 *
 * @author <huangtang>
 * @since 2022/4/13 14:27
 **/
public class FileChannelDemo1 {
    //FileChannel读取数据到buffer中
    public static void main ( String[] args ) throws Exception {
        //创建FileChannel
        RandomAccessFile aFile = new RandomAccessFile ("D:\\atguigu\\01.txt" , "rw");
        FileChannel channel = aFile.getChannel ();
        //创建Buffer
        ByteBuffer buf = ByteBuffer.allocate (1024);
        //FileChannel从文件中读取数据到buffer中，buffer中的数据读取完后position会等于limit
        int byteRead = channel.read (buf);
        //-1表示读取到文件末尾
        while (byteRead != -1) {
            System.out.println ("读取了" + byteRead);
            //调用该方法，将position赋给limit,position从头开始，后续才能从开头进行打印
            buf.flip ();//从读模式变为写模式
            while (buf.hasRemaining ()) {
                //当buf中还有字节时，从buffer缓冲区中打印数据
                System.out.println ((char) buf.get ());
            }
            buf.clear ();
            //还未读完时，继续进行读操作
            byteRead = channel.read (buf);
        }
        aFile.close ();
        System.out.println ("操作结束");
    }
}
